package com.lcj.OwnerMyBatis.config;

import com.lcj.OwnerMyBatis.Resources;
import com.lcj.OwnerMyBatis.pojo.Configuration;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import lombok.AllArgsConstructor;
import lombok.Data;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.beans.PropertyVetoException;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;

/**
 * @Author：liuchangjun
 * @Date：2021/10/26
 */
@Data
public class XMLConfigBuilder {

    private Configuration configuration;

    public XMLConfigBuilder() {
        this.configuration = new Configuration();
    }

    /**
     * 该方法解析配置文件，封装configuration
     * @param in
     * @return
     */
    public Configuration parseConfig(InputStream in) throws DocumentException, PropertyVetoException {
        Document document = new SAXReader().read(in);
        Element rootElement = document.getRootElement();
        List<Element> elementList = rootElement.selectNodes("//property");
        Properties properties = new Properties();
        for(Element element:elementList){
            String name = element.attributeValue(("name"));
            String value = element.attributeValue(("value"));
            properties.put(name,value);
        }
        //解析数据源
        ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
        comboPooledDataSource.setDriverClass(properties.getProperty("driverClass"));
        comboPooledDataSource.setJdbcUrl(properties.getProperty("jdbcUrl"));
        comboPooledDataSource.setUser(properties.getProperty("username"));
        comboPooledDataSource.setPassword(properties.getProperty("password"));
        this.configuration.setDataSource(comboPooledDataSource);

        //mapper.xml解析：拿到路径--字节输入流--dom4j解析
        List<Element> mapperList = rootElement.selectNodes("//mapper");
        for(Element element : mapperList){
            String mapperPath = element.attributeValue("resource");
            InputStream inputStream =  Resources.getResourceAsStream(mapperPath);
            XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(configuration);
            xmlMapperBuilder.parse(inputStream);
        }
        return configuration;
    }
}
